#!/bin/bash
# Print WiFi Access Point info for Armbian MOTD.
# Detects active hostapd instances, parses SSID + interface, shows channel via `iw`.

set -o pipefail

# one-time spacer after header (marks that something printed before Performance)
_motd_mark_after_header() {
  # prefer /run, fallback to user runtime or /tmp (works when not root)
  local base="/run/armbian-motd"
  mkdir -p "$base" 2>/dev/null || base="${XDG_RUNTIME_DIR:-/tmp}/armbian-motd"
  mkdir -p "$base" 2>/dev/null || return 0
  local stamp="${base}/.after_header.printed"
  [[ -e "$stamp" ]] || { echo ""; : >"$stamp"; }
}

safe_source() { [[ -f "$1" ]] && . "$1"; }

THIS_SCRIPT="ap-info"
MOTD_DISABLE=""

# Optional overrides
safe_source /etc/default/armbian-motd
for f in ${MOTD_DISABLE}; do
  [[ "${f}" == "${THIS_SCRIPT}" ]] && exit 0
done

# helper: pretty-print one AP line
print_ap_line() {
  local ssid="$1" iface="$2"
  local chan
  if command -v iw >/dev/null 2>&1; then
    # Grab the whole "channel ..." line from iw and use it as-is
    chan="$(iw dev "$iface" info 2>/dev/null \
      | sed -n 's/^[[:space:]]*channel[[:space:]]\+\(.*\)$/\1/p' \
      | head -1)"
  fi
  printf ' WiFi AP:      SSID: (\x1B[91m%s\x1B[0m), channel %s\n' \
    "$ssid" "${chan:-n/a}"
}

# detect active hostapd services
if systemctl is-active --quiet hostapd.service \
   || systemctl list-units 'hostapd@*.service' --state=active >/dev/null 2>&1; then

  # collect hostapd configs (classic and templated), skip non-existing
  confs=()
  for p in /etc/hostapd/hostapd.conf /etc/hostapd/hostapd-*.conf; do
    [[ -f "$p" ]] && confs+=("$p")
  done

  # print at most one line per iface+ssid combo
  declare -A _ap_printed=()
  first=1
  for cfg in "${confs[@]}"; do
    ssid="$(grep -E '^[[:space:]]*ssid[[:space:]]*='      "$cfg" | sed -E 's/.*=//;s/^[[:space:]]+|[[:space:]]+$//')"
    iface="$(grep -E '^[[:space:]]*interface[[:space:]]*=' "$cfg" | sed -E 's/.*=//;s/^[[:space:]]+|[[:space:]]+$//')"

    # fall back to iw to discover iface if config lacks it
    [[ -z "$iface" ]] && iface="$(iw dev 2>/dev/null | awk '/Interface/ {print $2; exit}')"

    key="${iface}|${ssid}"
    [[ -z "$ssid" || -z "$iface" || -n "${_ap_printed[$key]+x}" ]] && continue

    # print exactly one spacer before the first AP line
    if (( first )); then _motd_mark_after_header; first=0; fi

    print_ap_line "$ssid" "$iface"
    _ap_printed[$key]=1
  done
fi

# ensure zero exit when executed directly
(return 0 2>/dev/null) || exit 0
